package com.st.mall.product.excepiton;

import com.st.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

import static com.st.common.exception.BizCodeEnum.UNKNOWN_EXCEPTION;
import static com.st.common.exception.BizCodeEnum.VALID_EXCEPTION;

@Slf4j
@RestControllerAdvice(basePackages = "com.st.mall.product.controller")
public class GuliControllerExceptionAdvice extends Exception {

    /**
     *
     * @param manve 绑定异常处理
     * @return 异常JSON
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerBindException(MethodArgumentNotValidException manve){
        log.error("数据校验异常",manve.getMessage(),manve.getBindingResult());
        BindingResult br=manve.getBindingResult();
        Map<String,Object> map=new HashMap<>();
        if (br.hasErrors()) {
            br.getFieldErrors().forEach((fieldError)->{
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            });
        }
        return R.error(VALID_EXCEPTION.getCode(),VALID_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 除上面外其他所有异常处理
     * @param t 所有抛出异常
     * @return 异常JSON
     */
    @ExceptionHandler(value = Throwable.class)
    public R handlerAllOthersOfException(Throwable t){
        log.error(t.getMessage(),t);
        return R.error(UNKNOWN_EXCEPTION.getCode(), t.getMessage());
    }
}
